<template>
  <div>
    <div style="height: 40px; padding-top: 20px; padding-left: 10px;">
      <label style="float: left; margin-top: 3px; margin-right: 5px;">用户名:</label>
      <el-input v-model="userName" placeholder="请输入用户名" class="seache-user seache-username" clearable size="mini"></el-input>
      <label style="float: left; margin-top: 3px; margin-left: 7px; margin-right: 5px;">账号:</label>
      <el-input v-model="account" placeholder="请输入账号" class="seache-user seache-account" clearable size="mini"></el-input>
      <el-button type="primary" class="seach" @click="query()" icon="el-icon-search" size="mini">搜索</el-button>
    </div>
    <!--v-show:是否显示对应的按钮的图标-->
    <el-button type="danger" style="float: left; margin: 15px 0 10px 25px;" size="mini" @click="deleteDalog()"
      v-show="hasPerms('user:delete:read')" icon="el-icon-delete">删除</el-button>
    <el-button type="primary" style="float: left; margin: 15px 0 10px 15px;" size="mini" @click="dialogFormVisible = true"
      v-show="hasPerms('user:add:read')" icon="el-icon-plus">新增</el-button>
    <el-table :data="tableData" @selection-change="handleSelectionChange" border size="mini">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="id"></el-table-column>
      <el-table-column prop="imageUrl" label="头像">
        <template slot-scope="scope">
          <!--preview-src-list:开启大图预览功能-->
          <el-image style="width: 100px; height: 50px" :src="relativUrl + scope.row.imageUrl" :preview-src-list="[relativUrl + scope.row.imageUrl]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="用户名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="account" label="账号" :formatter="formatterAccount"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="qq" label="qq号"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column label="用户状态(锁定)">
        <template slot-scope="scope">
          <el-switch v-model='scope.row.locked == 2' active-color="#13ce66" inactive-color="#ff4949"
            @change="userswitch(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click='updateDalog(scope.row)' v-show="hasPerms('user:edit:read')"
            icon="el-icon-edit"></el-button>
          <el-button type="success" size="mini" @click='authorDalog(scope.row)'
            v-show="hasPerms('user:edit:read')">授权</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页部分 -->
    <PageInfo class="page-class" :totalCount="totalCount" :pageSize="pageSize" @pageSizes="pageChange"
      @pageCurrent="pageCurrent" />
    <!--新增用户-->
    <IndexAddView :dialog="dialogFormVisible" @dialogFormVisible="chidAddUser" />
    <IndexEditView :editdialog="editDialogFormVisible" :userInfo="userInfo" @editDialogFormVisible="chidEditUser" />

    <el-dialog title="用户授权" :visible.sync="authorDialog" class="author-dialog">
      <el-form :model="roleForm" ref="roleForm" label-width="80px">
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="roleForm.roleId" clearable multiple placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in roleNames" :key="item.roleId" :label="item.roleName" :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="authorDialog = false">取 消</el-button>
        <el-button type="primary" @click="authorUser()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import PageInfo from '../PageInfo.vue';
import IndexAddView from './indexAddView.vue';
import IndexEditView from './indexEditView.vue';
import { hasPermission } from '@/permission/index.js';

export default {
  data() {
    return {
      tableData: [],
      current: 1,
      pageSize: 8,
      totalCount: 0,
      userName: '',
      account: '',
      ids: [],
      relativUrl: 'http://127.0.0.1/images/',
      dialogFormVisible: false,
      editDialogFormVisible: false,
      authorDialog: false,
      userInfo: {},
      roleForm: {
        roleId: [],
      },
      roleNames: []
    }
  },
  components: {
    PageInfo,
    IndexAddView,
    IndexEditView
  },
  mounted() {

    this.getData()
  },
  methods: {
    pageChange(num) {
      this.pageSize = num;
      this.getData();
    },
    pageCurrent(res) {
      this.current = res;
      this.getData();
    },
    getData() {
      let reqUser = {
        "current": this.current,
        "size": this.pageSize,
        "username": this.userName,
        "account": this.account
      }
      this.$http({
        method: 'post',
        url: '/admin/userInfo/pageList',
        data: reqUser
      }).then(res => {
        this.tableData = res.data.data.data
        this.totalCount = res.data.data.total
      }).catch(error => {
        let statusCode = error.response.status;
        console.log(statusCode)
        switch (statusCode) {
          case 500:
            this.$message({
              message: "服务器系统异常",
              center: true,
              type: 'warning'
            })
            break;
          default:
            this.$message({
              message: "服务器系统异常",
              center: true,
              type: 'warning'
            })

        }
      })
    },
    formatterAccount(row, column) {
      return row.account == "" ? row.userName : row.account;
    },
    //禁用
    async userswitch(row) {
      let status = row.locked == 2 ? 1 : 2;
      let data = {
        "userId": row.id,
        "locked": status
      }
      await this.$http({
        url: '/admin/userInfo/update',
        method: 'post',
        Headers: {
          "Content-Type": 'application/json'
        },
        data: data
      }).then(res => {
        let result = res.data;
        if (result.code === 200) {
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
          //刷新列表
          this.getData();
        } else {
          this.$message({
            showClose: true,
            message: '操作失败',
            type: 'success'
          });
        }
      })
    },
    //勾选复选框赋值给ids，用于删除操作。
    handleSelectionChange(row) {
      this.ids.length = 0;
      console.log(this.ids.length)
      for (let i = 0; i < row.length; i++) {
        this.ids.push(row[i].id);
      }
      console.log(this.ids.length)
    },
    //查询按钮
    query() {
      this.getData();
    },
    //编辑
    updateDalog(row) {
      console.log(row.id)
      this.editDialogFormVisible = true;
      this.userInfo = row;
    },
    //删除逻辑
    deleteDalog: function () {
      let newIds = this.ids;
      console.log(this.ids)
      if (newIds.length <= 0) {
        this.$message({
          message: "请选择要删除的id",
          center: true,
          type: 'warning'
        })
        return
      }
      this.$confirm('此操作将永久删除数据，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          method: 'delete',
          url: '/admin/userInfo/delete/' + newIds,
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              message: '操作成功',
              type: 'success'
            });
            //刷新列表
            this.getData();
          } else {
            this.$message({
              showClose: true,
              message: '操作失败',
              type: 'success'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: '已取消删除'
        });
      })
    },
    chidAddUser(data) {
      this.dialogFormVisible = data;
      this.getData();
    },
    chidEditUser(data) {
      this.editDialogFormVisible = data;
      this.getData();
    },
    hasPerms: function (perms) {
      return hasPermission(perms);
    },
    //授权页面
    authorDalog(row) {
      this.authorDialog = true;
      let roles = row.roles;
      this.userId = row.id;
      this.roleForm.roleId = [];
      //获取所有角色
      this.$http({
        method: 'get',
        url: 'admin/role/list'
      }).then(res => {
        let result = res.data;
        if (result.code == 200) {
          let newData = result.data;
          this.roleNames = newData;
          for (let i = 0; i < newData.length; i++) {
            console.log("111:" + newData[i].roleId)
            for (let j = 0; j < roles.length; j++) {
              console.log("222:" + roles[j])
              if (roles[j] == newData[i].roleId) {
                this.roleForm.roleId.push(newData[i].roleId);
              }
            }
          }
        }
      })
    },
    authorUser() {
      let roles = this.roleForm.roleId;
      let userId = this.userId;
      let data = {
        "userId": userId,
        "roleIds": roles
      }
      this.$http({
        method: 'post',
        url: '/admin/userInfo/userAuthorize',
        Headers: {
          'Content-Type': 'application/json'
        },
        data: data
      }).then(res => {
        let result = res.data;
        if (result.code == 200) {
          this.authorDialog = false
          this.$message({
            type: 'success',
            message: "操作成功"
          })
          this.getData();
        }
      })
    }
  }
}

</script>


<style>
.seache-user {
  width: 180px;
  float: left;
}

.seach {
  float: left;
  margin-left: 20px;
}

.delete-user-btn {
  float: left;
  margin-bottom: 10px;
}

#table-user {
  height: 100%;
}

.el-dialog {
  width: 40%;
  text-align: left;
}

.author-dialog {
  width: 70%;
  text-align: center;
  margin: 0 auto;
}

.inser-input {
  width: 270px;
  float: left;
}

.dialog-footer {
  text-align: center;
}

/* 用户头像 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>